const app = getApp();
const d = new Date();
let currentDay = `${d.getFullYear()}-${d.getMonth()+1}-${d.getDate()}`;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    authLocationTips: false,
    franchiserIndex: '',
    franchisers: [], //加盟商列表
    dates: currentDay,
    dateSwitch: false,
    thrashIndex: "",
    thrashs: [], //打水模板
    rechargeIndex: "",
    recharges: [], //充值模板
    address: [],
    areaInfo_name: [],
    area_id_Info: [],
    pageType: 1, // 1添加  2修改
    ch_latitude: "",
    ch_longitude: '',
    input_val: "", //详细地址
    addressName: "", //园区名称
    otherThrashTitle: "", //兼容旧版 非当前加盟商的打水模板
    otherRechageTitle: "", //兼容旧版 非当前加盟商的用户自助充值模板
    disabled: false, //加盟商禁止选择
  },



  onReady: function () {
    this.dateTime = this.selectComponent("#dateTime");
    this.cascade = this.selectComponent("#cascade");
  },

  showCascade() {
    this.cascade.selection(this.data.area_id_Info);
  },

  cascadeComplete(e) {
    const detail = e.detail;
    this.setData({
      area_id_Info: detail.ids,
      areaInfo_name: detail.names
    })
  },

  //设置模板
  setTmeplate(temps, partner_id) {
    let results = [];
    temps.forEach(current => {
      if (current.partner_id == partner_id) {
        results.push(current);
      }
    })
    results.unshift({
      id: "",
      template_title: "通用模板"
    })

    return results;

  },

  //选择加盟商  处理到对应的打水和充值模板
  handleFranchiserChange(e) {
    const name = e.currentTarget.dataset.name;
    const index = e.detail.value;
    const partner_id = this.data.franchisers[index].id;
    let nthrashs = JSON.parse(JSON.stringify(this.thrashs));
    let nrecharges = JSON.parse(JSON.stringify(this.recharges));
    let thrashs = this.setTmeplate(nthrashs, partner_id);
    let recharges = this.setTmeplate(nrecharges, partner_id);
    this.setData({
      thrashIndex: this.data.franchiserIndex == index ? index : '',
      rechargeIndex: this.data.franchiserIndex == index ? index : '',
      [name]: index,
      thrashs,
      recharges
    })
  },


  handleChange(e) {
    const name = e.currentTarget.dataset.name;
    this.setData({
      [name]: e.detail.value
    })
  },

  showDateTime() {
    this.dateTime.show();
  },

  changeDateTime(e) {
    this.setData({
      dates: e.detail.result
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.from = options.from || '';
    const id = options.id; //园区id
    const partner_id = options.partner_id;
    Promise.all([this.getFranchises(), this.getTemplate(1), this.getTemplate(2)])
      .then(([franchisers, recharges, thrashs]) => {
        console.log(franchisers, recharges, thrashs);
        this.setData({
          franchisers
        })
        this.recharges = recharges;
        this.thrashs = thrashs;
        if (id) {
          this.getVillageInfo(partner_id);
        }
        if (options.from == 'middle') {
          let index = franchisers.findIndex(item => item.id == options.partner_id);
          let nthrashs = JSON.parse(JSON.stringify(this.thrashs));
          let nrecharges = JSON.parse(JSON.stringify(this.recharges));
          let thrashs = this.setTmeplate(nthrashs, partner_id);
          let recharges = this.setTmeplate(nrecharges, partner_id);
          this.setData({
            disabled: true,
            franchiserIndex: ~index ? index : '',
            thrashs,
            recharges
          })
        }
      }).catch(e => {
        app.showToast(e);
      });
    let pageType = 1,
      title = "添加园区";
    if (id) {
      pageType = 2;
      this.id = id;
      title = "修改园区";
    }
    wx.setNavigationBarTitle({
      title
    })
    this.setData({
      pageType
    })
  },





  //获取加盟商列表
  getFranchises() {
    return new Promise((resolve, reject) => {
      app.ajax({
        url: 'Partner/Franchiser/franchiserList',
        data: {
          row: 100
        },
        success: res => {
          if (res.data.code == 5000) {
            resolve(res.data.data)
          } else {
            reject(res.data.message || '服务器异常')
          }
        },
        error: e => {
          reject("网络错误")
        }
      })
    })
  },

  getVillageInfo(partner_id) {
    app.ajax({
      url: "Partner/Franchiser/findFranchiserVillage",
      data: {
        id: this.id,
        partner_id
      },
      success: res => {
        if (res.data.code > 0) {

          console.log(res.data.data);
          const data = res.data.data;
          const franchisers = this.data.franchisers;
          let fIndex = franchisers.findIndex(current => current.id == data.partner_id);
          let thrashs = this.setTmeplate(this.thrashs, data.partner_id);
          let recharges = this.setTmeplate(this.recharges, data.partner_id);
          let tIndex = thrashs.findIndex(current => current.id == data.sell_id);
          let rIndex = recharges.findIndex(current => current.id == data.template_id);

          this.setData({
            thrashs,
            recharges,
            franchiserIndex: ~fIndex ? fIndex : '',
            rechargeIndex: ~rIndex ? rIndex : '',
            thrashIndex: ~tIndex ? tIndex : '',
            otherRechageTitle: rIndex == -1 ? data.template_title : "",
            otherThrashTitle: tIndex == -1 ? data.sell_water_title : "",
            dateSwitch: data.check_record_card == 1 ? true : false,
            dates: data.check_record_card == 1 ? data.check_record_card_time : currentDay,
            areaInfo_name: [data.province_name, data.city_name, data.area_name],
            area_id_Info: [data.province, data.city, data.area],
            ch_latitude: data.lat || '',
            ch_longitude: data.lng || '',
            addressName: data.village_name,
            input_val: data.address
          })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },


  //获取模板信息   1充值模板 2打水模板
  getTemplate(template_species) {
    return new Promise((resolve, reject) => {
      app.ajax({
        url: "Partner/Village/templateList",
        data: {
          row: 9999,
          template_species,
          type: 1,
          template_status: 1
        },
        success: res => {
          if (res.data.code > 0) {
            resolve(res.data.data.data);
          } else {
            reject(res.data.message || "服务器异常")
          }
        },
        error: e => {
          reject("网络错误")
        }
      })
    })
  },


  addressChange(e) {
    const address = e.detail.address;
    this.setData({
      areaInfo_name: address.areaInfo_name,
      area_id_Info: address.area_id_Info
    })
  },


  navMapSetting() {
    if (this.data.areaInfo_name.length == 0) {
      app.showToast("请先选择园区地址", "none", 2000, function () {});
      return;
    }
    wx.getSetting({
      success: settingRes => {
        if (settingRes.errMsg === "getSetting:ok") {
          const setting = settingRes.authSetting;
          if (setting["scope.userLocation"] == undefined || setting["scope.userLocation"]) {
            if (!this.data.ch_latitude || !this.data.ch_longitude) {
              wx.getLocation({
                type:"gcj02",
                success: results => {
                  this.setData({
                    ch_latitude: results.latitude,
                    ch_longitude: results.longitude
                  })
                  this.openLocation();
                },
                fail: res => {
                  app.showToast("请检查是否打开手机定位功能");
                }
              })
            } else {
              this.openLocation();
            }
          } else if (setting["scope.userLocation"] == false) {
            this.setData({
              authLocationTips: true
            })
          }
        }
      },
      fail: e => {
        app.showToast("getSetting fail");
      }
    })
  },

  openLocation() {
    wx.chooseLocation({
      latitude: this.data.ch_latitude - 0,
      longitude: this.data.ch_longitude - 0,
      success: res => {
        if (res.errMsg === "chooseLocation:ok") {
          this.setData({
            input_val: res.name,
            ch_longitude: res.longitude,
            ch_latitude: res.latitude
          })
        }
        console.log(res, "results")
      },
      fail: e => {
        if (e.errMsg === "chooseLocation:fail auth deny") {
          this.setData({
            authLocationTips: true
          })
        }
      }
    })
  },

  handleOpenSetting() {
    wx.openSetting({
      success: res => {
        if (res.errMsg === "openSetting:ok") {
          if (res.authSetting["scope.userLocation"]) {
            this.setData({
              authLocationTips: false
            })
            this.openLocation()
          }
        }
      },
      fail: e => {
        app.showToast("打开设置失败");
      }
    })
  },


  closeLocationTips() {
    this.setData({
      authLocationTips: false
    })
  },




  submit() {
    const village_name = this.data.addressName;
    if (village_name == "") {
      app.showToast("请输入园区名称");
      return false;
    }
    const franchiserIndex = this.data.franchiserIndex;
    if (franchiserIndex === "") {
      app.showToast("请选择加盟商");
      return false;
    }
    const thrashIndex = this.data.thrashIndex;
    if (thrashIndex === "") {
      app.showToast("请选择价格模板");
      return false;
    }
    const rechargeIndex = this.data.rechargeIndex;
    if (rechargeIndex === "") {
      app.showToast("请选择自助充值模板");
      return false;
    }
    const areaInfo_name = this.data.areaInfo_name;
    const area_id_Info = this.data.area_id_Info;
    if (areaInfo_name.length == 0) {
      app.showToast("请选择园区地址");
      return false;
    }
    const address = this.data.input_val;
    if (address == "") {
      app.showToast("请输入详细地址");
      return false;
    }
    const pageType = this.data.pageType;
    const data = {
      partner_id: this.data.franchisers[franchiserIndex].id,
      template_id: this.data.recharges[rechargeIndex].id,
      set_template_id: this.data.thrashs[thrashIndex].id,
      village_name,
      province: area_id_Info[0],
      city: area_id_Info[1],
      area: area_id_Info[2],
      province_name: areaInfo_name[0],
      city_name: areaInfo_name[1],
      area_name: areaInfo_name[2],
      address,
      lat: this.data.ch_latitude,
      lng: this.data.ch_longitude,
      check_card_record: this.data.dateSwitch == true ? 1 : 2,
      check_record_card_time: this.data.dateSwitch == true ? this.data.dates : "",
    }
    let url = "Partner/Franchiser/addFranchiserVillage";
    if (pageType == 2) {
      url = "Partner/Franchiser/editFranchiserVillage";
      data.id = this.id
    }
    wx.showLoading({
      mask: true,
    })
    app.ajax({
      url,
      data,
      success: res => {
        wx.hideLoading();
        if (res.data.code > 0) {
          app.showToast(res.data.message, "success");
          if (this.from == 'middle') {
            console.log(res.data.data, "res.data.data")
            let results = res.data.data;
            const pages = getCurrentPages();
            let page = pages[pages.length - 3];
            let village = {
              id: results.village_id,
              ...results.data
            }
            page.setData({
              village,
              longitude: results.data.lng,
              latitude: results.data.lat,
              address: results.data.address
            })
            setTimeout(() => {
              wx.navigateBack({
                delta: 2,
              })
            }, 1500)
          } else {
            setTimeout(() => {
              const pages = getCurrentPages();
              let target = pages[pages.length - 2];
              target.reloadData();
              wx.navigateBack()
            }, 1500)
          }
        } else {
          app.showToast(res.data.message)
        }
      },
      error: e => {
        wx.hideLoading()
      }
    })
  },



  // 开启/关闭限制时间
  limitTime: function (e) {
    this.setData({
      dateSwitch: !this.data.dateSwitch
    })
  },


})